package com.knight.hadoop.day04.mythread.thread.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MyReentrantReadWriteLock {
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

	public static void main(String[] args) {
		
		MyReentrantReadWriteLock myReentrantReadWriteLock = new MyReentrantReadWriteLock();
		new Thread() {
			@Override
			public void run() {
				myReentrantReadWriteLock.get(Thread.currentThread());
				myReentrantReadWriteLock.write(Thread.currentThread());
			}
		}.start();

		new Thread() {

			@Override
			public void run() {
				myReentrantReadWriteLock.get(Thread.currentThread());
				myReentrantReadWriteLock.write(Thread.currentThread());
			}
		}.start();
	}

	/**
	 * 读操作
	 * 
	 * @param thread
	 */
	public void get(Thread thread) {
		lock.readLock().lock();
		try {
			long start = System.currentTimeMillis();
			while (System.currentTimeMillis() - start <= 1) {
				System.out.println(thread.getName() + ":正在进行读操作");
			}
			System.out.println(thread.getName() + ":读操作完毕");
		} finally {
			lock.readLock().unlock();
		}
	}

	public void write(Thread thread) {
		lock.writeLock().lock();
		try {
			long start = System.currentTimeMillis();
			while (System.currentTimeMillis() - start <= 1) {
				System.out.println(thread.getName() + ":正在进行写操作");
			}
			System.out.println(thread.getName() + ":写操作完毕");
		} finally {
			lock.writeLock().unlock();
		}
	}

}
